<template>
	<view>
		<view class="container">
			<!-- 圆形小logo -->
			<!-- <view class="logo-container">
			  <image class="logo" src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/20250723-184216.jpeg" mode="aspectFit"></image>
			</view> -->
      <!-- 背景图 -->
      <view class="background-image">
        <image style="width: 100%;" src="https://tongrenlijiaojing.oss-cn-beijing.aliyuncs.com/wechat/activeInvite/login_back.png" mode="widthFix"></image>
      </view>
      <input class="input-nickname" v-model="childName" placeholder="请输入姓名"/>
      <picker class="input-birthday" style=" flex: 1;"  v-model="childBirth" mode='date' :start=minDate :end=maxDate @change="setBirthDay">
        <view :style="!childBirth?'color:#8a8383;':''">
          {{childBirth?childBirth:'选择生日'}}
        </view>
      </picker>
      <view class="form-phone">
        <view class="input-group">
          <input class="input" type="number" v-model="phone" maxlength="11" disabled/>
          <button class="input-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">获取手机号</button>
        </view>
      </view>
      <!-- <view class="sub_title">欢迎来到小虎点点</view> -->
			<!-- 授权登录按钮 -->
      <button class="login-btn" @click="submitForm">登录</button>
			<!-- 隐私保护协议 -->
			<!-- <view class="agreement">
				<checkbox :checked="agreed" @change="handleAgreeChange" />我已阅读并同意<text class="link">《隐私保护协议》</text>
			</view> -->
		</view>
	</view>
</template>

<script>
  export default {
    data() {
      return {
        phone: '',
        childName: '',
        childBirth: '',
        agreed: false,
        minDate: '',
			  maxDate: '',
      }
    },
    onShow() {
      const that = this
      // 初始化日期选择范围
      const now = new Date()
      this.minDate = new Date(now.getFullYear() - 10, 0).toISOString().slice(0, 7)
      this.maxDate = new Date(now.getFullYear() - 1, 11).toISOString().slice(0, 7)
      
      // 获取当前页面路径，避免重复跳转
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      const currentPath = currentPage.route;
      
      // 如果当前已经是登录页面，不设置islogout=true，避免重复跳转
      if (currentPath !== 'pages/index/login') {
        uni.setStorageSync('islogout', true)
      }
      
      this.$tools.setStorageOpenid(that.checkIsRegist);
    },
    methods: {
      handleLogin(e) {
        if (!this.agreed) {
          uni.showToast({
            title: '请先同意隐私保护协议',
            icon: 'none'
          });
          return;
        }
        if (e.detail.userInfo) {
          // 处理登录逻辑
          console.log('用户信息:', e.detail.userInfo);
          // 这里可以添加跳转到主页或其他操作
        } else {
          uni.showToast({
            title: '授权失败',
            icon: 'none'
          });
        }
      },
      
      getPhoneNumber(e) {
        const that = this
        const openid = uni.getStorageSync('openid') || '';
        this.$http.POST('/app/user/login/getPhoneNumber', { 
          code: e.detail.code, 
          openid: openid,
          registAdminQrcodeId: uni.getStorageSync('lastQrcodeId') || 0,
          registAdminId: uni.getStorageSync('lastAdminId') || 0,
          registChannelId: uni.getStorageSync('lastChannelId') || 0,
          qrcodeId: uni.getStorageSync('lastQrcodeId') || 0,
          darenName: uni.getStorageSync('lastDarenName') || ''
        }, function (res) {
          console.log('成功获取手机号信息', res);
          uni.setStorageSync('token', res.data.token);
          uni.setStorageSync('refreshToken', res.data.refreshToken);
          uni.removeStorageSync('islogout');
          that.getUserPhone()
        })
        // this.$http.POST('/app/user/login/getPhoneNumber', { 
        //   code: e.detail.code, 
        //   openid: openid
        // }, function (res) {
        //   console.log('成功获取手机号信息', res);
        //   uni.setStorageSync('token', res.data.token);
        //   uni.setStorageSync('refreshToken', res.data.refreshToken);
        //   uni.removeStorageSync('islogout');
        //   // 获取页面栈
        //   const pages = getCurrentPages();
        //   if (pages.length > 1) {
        //     // 有上一级页面，返回上一级
        //     console.log('有上一级页面，返回上一级');
        //     uni.navigateBack();
        //   } else {
        //     // 没有上一级页面，返回首页
        //     console.log('没有上一级页面，返回首页');
        //     that.$tools.routerTo('/pages/index/index', 'switchTab', 'none')
        //   }
        // })
      },
      getUserPhone() {
        if (!uni.getStorageSync('token')) {
          return
        }
        const that = this
        that.$http.GET('/app/user/info/person', {}, res => {
          console.log('获取用户信息', res);
          that.phone = res.data.phone
        })
      },
      // getPhoneNumber(e) {
      //   const that = this;
      //   uni.setStorageSync('islogout', false)
      //   const openid = uni.getStorageSync('openid') || '';
      //   this.$http.POST('/admin/student/student/getPhoneNumber', { code: e.detail.code, openid: '1234' }, function (res) {
      //       console.log('成功获取手机号信息');
      //   })
      // },
      checkIsRegist() {
        if (!uni.getStorageSync('token')) {
          return
        }
        const that = this
        that.$http.GET('/app/user/info/person', {}, res => {
          if (res.data.nickName !== '新用户') {
            uni.showToast({ title: '自动登录成功，请继续操作~', icon: 'none' })
            // that.isRegist = true // 标记为已经注册
            // 等待1秒后跳转
            setTimeout(() => {
              that.jumpPrePage();
            }, 1500);
          }
        })
      },
      submitForm() {
        const that = this
        // 如果已经注册则直接弹二维码，并且提示已预约
        if (this.isRegist) {
          uni.showToast({ title: '您已注册，已自动登录，请继续操作~', icon: 'none' })
          setTimeout(() => {
            that.jumpPrePage();
          }, 1500);
          return 
        }
        // 表单验证
        if (!this.phone || !/^1[3-9]\d{9}$/.test(this.phone)) {
          return uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
        }
        if (!this.childName) {
          return uni.showToast({ title: '请输入孩子姓名', icon: 'none' })
        }
        if (!this.childBirth) {
          return uni.showToast({ title: '请选择孩子生日', icon: 'none' })
        }

        try {
          // 提交表单数据
          that.$http.POST('/app/user/info/updateBasicInfo', {
            nickName: this.childName,
            birthday: this.childBirth,
          }, res => {
              that.jumpPrePage();
          }, res => {
            uni.showToast({ title: res.message || '登陆失败', icon: 'none' })
          })
        } catch (error) {
          console.error('登陆失败', error)
          uni.showToast({ title: '网络异常，请重试', icon: 'none' })
        }
      },
      jumpPrePage() {
        const that = this
        // 获取页面栈
        const pages = getCurrentPages();
        if (pages.length > 1) {
          // 有上一级页面，返回上一级
          console.log('有上一级页面，返回上一级');
          uni.navigateBack();
        } else {
          // 没有上一级页面，返回首页
          console.log('没有上一级页面，返回首页');
          that.$tools.routerTo('/pages/index/index2', 'switchTab', 'none')
        }
      },
      setBirthDay(e) {
        this.childBirth = e.detail.value;
      },
      handleAgreeChange(e) {
        this.agreed = e.detail.value;
      }
    }
  }
</script>

<style>
.input {
  width: 60vw;
	height: 13vw;
	border-radius: 8rpx;
	padding: 0 20rpx;
	top: 103vw;
	left: 19vw;
	position: absolute;
	z-index: 10;
	font-size: 5vw;
}

.input-nickname {
  	width: 55vw;
    height: 13vw;
    border-radius: 8rpx;
    padding: 0 20rpx;
    top: 58.5vw;
    left: 16vw;
    position: absolute;
    z-index: 10;
    font-size: 5vw;
}

.input-birthday {
  	width: 55vw;
    height: 16vw;
    border-radius: 8rpx;
    padding: 0 20rpx;
    top: 83.5vw;
    left: 16vw;
    position: absolute;
    z-index: 10;
    font-size: 5vw;
}

.input-btn {
  	width: 32vw;
    padding: 0px;
    top: 103vw;
    left: 56vw;
	  height: 13vw;
    position: absolute;
    z-index: 10;
    font-size: 5vw;
    border: 0;
    color: #089790;
	background-color: #F6F6F6;
}
.input-btn::after {
	border: none;
}

.background-image {
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
}
.sub_title {
  font-size: 18px;
  text-align: center;
  margin-bottom: 50px;
}
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* justify-content: center; */
  height: 100vh;
  padding: 20px;
  padding-top: 15vh;
}

.logo-container {
  margin-bottom: 20px;
}

.logo {
  width: 150px;
  height: 150px;
  border-radius: 50%;
}

.login-btn {
  top: 109vw;
  width: 63%;
  margin-bottom: 20px;
  background-color: #00BAAD;
  color: white;
  border-radius: 50px;
  font-size: 18px;
}

.agreement {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.link {
  color: #007AFF;
}
</style>